package com.ezandroid.library.network.util;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;
import java.util.Set;

/**
 * Url encoder util.
 *
 * @author markmjw
 * @date 2015-04-22
 */
public class UrlEncoder {

    /**
     * Encode url parameters.
     *
     * @param params
     * @param encoding
     * @return
     */
    public static String encode(Map<String, String> params, String encoding) {
        StringBuilder encodedParams = new StringBuilder();
        try {
            Set<Map.Entry<String, String>> entrySet = params.entrySet();
            int size = entrySet.size();
            int index = 0;
            for (Map.Entry<String, String> entry : entrySet) {
                encodedParams.append(URLEncoder.encode(entry.getKey(), encoding));
                encodedParams.append('=');
                encodedParams.append(URLEncoder.encode(entry.getValue(), encoding));
                if (++index < size) {
                    encodedParams.append('&');
                }
            }
            return encodedParams.toString();
        } catch (UnsupportedEncodingException uee) {
            throw new RuntimeException("Encoding not supported: " + encoding, uee);
        }
    }
}
